﻿using System;
using VideoStore.Business.Facade;
using VideoStore.Domain.Entities;
using VideoStore.Services.Dto;
using VideoStore.Services.Interface;
using VideoStore.Common.Response;
using VideoStore.Common.Response.Extension;
using VideoStore.Services.Translation;
using VideoStore.Services.Translation.Base;
using VideoStore.Services.Translation.Factory;

namespace VideoStore.Services
{
    public class StoreService : IStoreService
    {
        #region Implementation of IStoreService

        /// <summary>
        /// Gets the store by id.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        public Response<StoreDto> GetStoreById(int id)
        {
            var response = new Response<StoreDto>();
            response.IsSuccessful = true;
            try
            {
                var facade = VideoStoreFacade.Instance;
                Store store = facade.GetStoreById(id);
                ITranslator translator = TranslatorFactory.GetTranslatorByType(typeof(StoreTranslator));
                response.ResponseObject = translator.TranslateToDto<Store, StoreDto>(store);
            }
            catch (Exception ex)
            {
                response.IsSuccessful = false;
                response.Errors.AddFatalError(ex.Message);
            }
            return response;
        }

        /// <summary>
        /// Creates the store.
        /// </summary>
        /// <param name="newStore">The new store.</param>
        /// <returns></returns>
        public Response<StoreDto> CreateStore(StoreDto newStore)
        {
            var response = new Response<StoreDto>();
            response.IsSuccessful = true;
            try
            {
                var facade = VideoStoreFacade.Instance;
                ITranslator translator = TranslatorFactory.GetTranslatorByType(typeof(StoreTranslator));
                Store storeEntity = translator.TranslateToEntity<StoreDto, Store>(newStore);
                Store savedStore = facade.CreateStore(storeEntity);
                response.ResponseObject = translator.TranslateToDto<Store, StoreDto>(savedStore);
                response.Messages.AddSuccessfulSaveMessage("Store");
            }
            catch (Exception ex)
            {
                response.IsSuccessful = false;
                response.Errors.AddFatalError(ex.Message);
            }
            return response;
        }

        #endregion
    }
}
